<template>
  <div class="log-container">
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-item">
        <span>开始日期</span>
        <el-date-picker
            v-model="startTime"
            type="date"
            placeholder="选择开始日期"
            value-format="YYYY-MM-DD"
            style="width: 160px"
        />
      </div>
      <div class="filter-item">
        <span>结束日期</span>
        <el-date-picker
            v-model="endTime"
            type="date"
            placeholder="选择结束日期"
            value-format="YYYY-MM-DD"
            style="width: 160px"
        />
      </div>
      <div class="filter-item">
        <span>门店</span>
        <el-select
            v-model="selectedStore"
            placeholder="请选择门店"
            style="width: 200px"
        >
          <el-option
              v-for="store in stores"
              :key="store.value"
              :label="store.label"
              :value="store.value"
          />
        </el-select>
      </div>
      <div class="filter-item">
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </div>
      <div class="filter-item">
        <el-button type="warning" @click="handleExport">导出</el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="id" label="工号" width="80" />
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="store" label="所属门店" width="150" />
        <el-table-column prop="roleName" label="职位" width="100" />
        <el-table-column prop="loginTime" label="登录时间" width="200" />
        <el-table-column prop="quitTime" label="退出时间" width="200" />
        <el-table-column prop="ipAddress" label="登录IP" width="150" />
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="totalData"
          layout="total, prev, pager, next, jumper"
          @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import {ElMessage} from "element-plus";

// 数据相关变量
const tableData = ref([]);
const stores = ref([]);
const selectedStore = ref('');
const dateRange = ref(null);
const currentPage = ref(1);
const pageSize = ref(10);
const totalData = ref(100);
// 修改日期相关变量
const startTime = ref(null);
const endTime = ref(null);
// 获取门店数据
const getStores = () => {
  axios.get(`/store/getStoreName`).then(res => {
    stores.value = res.data.map(item => ({
      value: item.id,
      label: item.name
    }));
  });
};

// 获取访问日志数据
const getLogData = () => {

};

// 查询方法
const handleSearch = () => {
  // 修正参数名称为storeId，保持与DTO一致
  const requestBody = {
    storeId: selectedStore.value,
    startTime: startTime.value,
    endTime: endTime.value
  };

  // 构建分页路径参数
  const pageNum = currentPage.value;
  const pageSizeVal = pageSize.value;

  // 过滤空值参数（保留false/0等有效值）
  const filteredBody = Object.fromEntries(
      Object.entries(requestBody).filter(([_, v]) => v !== null && v !== undefined && v !== '')
  );

  axios.post(`/loginInfo/search/${pageNum}/${pageSizeVal}`, filteredBody)
      .then(response => {
        tableData.value = response.data.obj.records;
        totalData.value = response.data.obj.total;
        ElMessage.success('查询成功');
      })
      .catch(error => {
        console.error('查询失败:', error);
        ElMessage.error(error.response?.data?.message || '查询失败');
      });
};

// 导出方法
const handleExport = () => {
  axios.get('/loginInfo/export', {
    responseType: 'blob', // 关键参数声明二进制流
    params: { // 传递筛选参数（与查询逻辑一致）
      storId: selectedStore.value,
      startTime: dateRange.value?.[0]?.toISOString(),
      endTime: dateRange.value?.[1]?.toISOString()
    }
  }).then(res => {
    // 创建Blob链接并触发下载
    const blob = new Blob([res.data], { type: res.headers['content-type'] });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');

    // 从响应头获取文件名（需后端配合）
    const fileName = decodeURIComponent(
        res.headers['content-disposition'].split('filename*=UTF-8\'\'')[1] ||
        '登录日志.xlsx'
    );

    link.href = url;
    link.download = fileName;
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();

    // 清理资源
    window.URL.revokeObjectURL(url);
    document.body.removeChild(link);
    ElMessage.success('导出成功');
  }).catch(err => {
    ElMessage.error('导出失败：' + (err.response?.data?.message || '未知错误'));
  });
};

// 删除方法
const handleDelete = (row) => {
  axios.delete(`/loginInfo/deleteLoginInfo/${row.id}`).then(res=>{
    ElMessage.success("删除成功");
    initData();
  }).catch(err=>{
    ElMessage.error("删除失败");
  })
};

// 分页变化处理
const handlePageChange = (page) => {
  currentPage.value = page;
  initData();
  getLogData();
};
// 初始化所有数据
const initData = () => {
  axios.get(`/loginInfo/getAll/${currentPage.value}/${pageSize.value}`).then(resp => {
    tableData.value = resp.data.obj.records;
    totalData.value = resp.data.obj.total
  })
};
// 初始化
onMounted(() => {
  getStores();
  getLogData();
  initData();
});
</script>

<style scoped>
.log-container {
  padding: 20px;
}

.filter-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.filter-item {
  display: flex;
  align-items: center;
  margin-right: 20px;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: flex-end;
}
</style>